import React, { PureComponent } from 'react'

import { connect } from 'dva'
import { PageHeaderWrapper } from '@ant-design/pro-layout'

import {
  Table,
  Card,
  Row,
  Col,
  message,
  Button,
  Form,
  Tabs,
  Modal,
  InputNumber
} from 'antd'
import SplitBillService from './services/splitBill'
import { p } from 'puppeteer/lib/USKeyboardLayout'

const { TabPane } = Tabs

@connect()
@Form.create()
class Bills extends PureComponent {
  state = {
    ledgerLoading: true,
    ledgerCurrent: 1,
    ledgerPageNumber: 1,
    ledgerPageSize: 10,
    ledgerTableData: [],
    ledgerTotal: 0,
    withDrawLoading: true,
    withDrawCurrent: 1,
    withDrawPageNumber: 1,
    withDrawPageSize: 10,
    withDrawTableData: [],
    withDrawTotal: 0,
    lastWithDrawAmount: 0,
    totalBalance: 0,
    totalWithDrawAmount: 0,
    withDrawAmount: 0,
    withDrawModal: false,
    withDrawDetailModal: false,
    withDrawData: []
  }

  withDrawStatus = {
    '01': '提现申请',
    '02': '审核拒绝',
    '03': '审核通过',
    '04': '转账成功',
    '05': '转账失败'
  }

  ledgerColumns = [
    {
      title: 'Id',
      dataIndex: 'id',
      width: 80
    },
    {
      title: '交易金额(元)',
      dataIndex: 'tradeAmount',
      width: 120,
      render: (text, record) => {
        return (
          <div>
            <a
              style={{
                color: 'green',
                display: record.tradeOp === '01' ? 'block' : 'none'
              }}
            >
              +{text}
            </a>
            <a
              style={{
                color: 'red',
                display: record.tradeOp === '02' ? 'block' : 'none'
              }}
            >
              -{text}
            </a>
          </div>
        )
      }
    },
    {
      title: '交易后余额(元)',
      dataIndex: 'tradedBalance',
      width: 140
    },
    {
      title: '交易类型',
      dataIndex: 'tradeType',
      width: 100,
      render: text =>
        text === '01'
          ? '结算'
          : text === '02'
          ? '付费'
          : text === '03'
          ? '提现'
          : text === '04'
          ? '退款'
          : text === '05'
          ? '增值服务'
          : '其它'
    },
    {
      title: '备注',
      dataIndex: 'remark',
      width: 250
    },
    {
      title: '来源id/去路id',
      dataIndex: 'sourceId',
      width: 120
    },
    {
      title: '交易时间',
      dataIndex: 'createTime',
      width: 180
    }
  ]

  withDrawColumns = [
    {
      title: 'Id',
      dataIndex: 'id',
      width: 80
    },
    {
      title: '提现金额(元)',
      dataIndex: 'amount',
      width: 200
    },
    {
      title: '提现状态',
      dataIndex: 'status',
      render: text => this.withDrawStatus[text]
    },
    {
      title: '交易时间',
      dataIndex: 'createTime',
      width: 180
    },
    {
      title: '操作',
      align: 'center',
      key: 'action',
      fixed: 'right',
      render: (text, record) => {
        return (
          <div className="table-action">
            <a onClick={() => this.showWithdrawDetailModal(record.id)}>查看</a>
          </div>
        )
      }
    }
  ]

  componentDidMount() {
    this.initData()
  }

  initData = () => {
    // 查询资金余额
    this.getBalance()
    // 查询资金流水
    this.getLedgerRecords()
    // 查询提现记录
    this.getWithDrawRecords()
  }

  // 查询资金余额
  getBalance() {
    SplitBillService.getBalance().then(res => {
      this.setState({
        totalBalance: res.totalBalance,
        lastWithDrawAmount: res.lastWithDrawAmount,
        totalWithDrawAmount: res.totalWithDrawAmount
      })
    })
  }

  // 查询资金流水
  getLedgerRecords() {
    const payload = {
      pageNumber: this.state.ledgerPageNumber,
      pageSize: this.state.ledgerPageSize
    }

    this.setState(
      {
        ledgerLoading: true
      },
      () => {
        SplitBillService.getLedgerRecords(payload).then(res => {
          message.success('获取信息成功')
          this.setState({
            ledgerTableData: res.records,
            ledgerTotal: res.total,
            ledgerLoading: false,
            ledgerCurrent: res.current
          })
        })
      }
    )
  }

  // 查询提现记录
  getWithDrawRecords() {
    const payload = {
      pageNumber: this.state.withDrawPageNumber,
      pageSize: this.state.withDrawPageSize
    }

    this.setState(
      {
        withDrawLoading: true
      },
      () => {
        SplitBillService.getWithDrawRecords(payload).then(res => {
          this.setState({
            withDrawTableData: res.records,
            withDrawTotal: res.total,
            withDrawLoading: false,
            withDrawCurrent: res.current
          })
        })
      }
    )
  }

  // 资金流水-分页，下一页
  ledgerOnChange = pageNumber => {
    this.setState(
      {
        ledgerPageNumber: pageNumber
      },
      () => {
        this.getLedgerRecords()
      }
    )
  }

  // 资金流水-切换每页数量
  ledgerOnShowSizeChange = (current, pageSize) => {
    this.setState({ ledgerPageNumber: 1, ledgerPageSize: pageSize }, () => {
      this.getLedgerRecords()
    })
  }

  // 提现申请-分页，下一页
  withdrawOnChange = pageNumber => {
    this.setState(
      {
        withDrawPageNumber: pageNumber
      },
      () => {
        this.getWithDrawRecords()
      }
    )
  }

  // 提现申请-切换每页数量
  withdrawOnShowSizeChange = (current, pageSize) => {
    this.setState({ withDrawPageNumber: 1, withDrawPageSize: pageSize }, () => {
      this.getWithDrawRecords()
    })
  }

  showLedgerTotal = () => {
    return `共有${this.state.ledgerTotal}条`
  }

  showWithDrawTotal = () => {
    return `共有${this.state.withDrawTotal}条`
  }

  // 申请提现
  showWithdrawModal = () => {
    if (this.state.lastWithDrawAmount > 0) {
      message.error(
        '您当前有在进行中的提现交易，在提现未完成之前禁止多次提现。'
      )
    } else {
      this.setState({
        withDrawModal: true
      })
    }
  }

  // 关闭申请提现
  cancelWithDrawModal = () => {
    this.setState({
      withDrawModal: false
    })
  }

  // 申请提现模态框
  renderWithDraw() {
    const { withDrawAmount, withDrawModal } = this.state

    const handleOk = e => {
      e.preventDefault()

      if (withDrawAmount > 0) {
        const payload = {
          amount: this.state.withDrawAmount
        }

        SplitBillService.withDraw(payload).then(res => {
          message.success('提现申请提交成功。')
          this.setState({
            withDrawModal: false
          })
          this.getBalance()
          this.getWithDrawRecords()
        })
      } else {
        message.error('请填写正确的提现金额。')
      }
    }

    const onChange = price => {
      this.setState({
        withDrawAmount: price
      })
    }

    return (
      <div>
        <Modal
          title="提现申请"
          visible={withDrawModal}
          onOk={handleOk}
          onCancel={this.cancelWithDrawModal}
        >
          申请金额：
          <InputNumber
            style={{ width: '150px' }}
            value={withDrawAmount}
            onChange={onChange}
          />
          &emsp;元
        </Modal>
      </div>
    )
  }

  // 查看提现详情
  showWithdrawDetailModal = id => {
    const payload = {
      sourceId: id
    }

    SplitBillService.getWithdrawDetail(payload).then(res => {
      this.setState({
        withDrawData: res,
        withDrawDetailModal: true
      })
    })
  }

  // 关闭提现详情模态框
  cancelWithdrawDetailModal = () => {
    this.setState({
      withDrawDetailModal: false,
      withDrawData: []
    })
  }

  // 提现详情模态框
  renderWithDrawDetail() {
    const { withDrawDetailModal } = this.state

    return (
      <div>
        <Modal
          title="提现申请详情"
          width="50%"
          bodyStyle={{ maxHeight: '450px', overflowY: 'scroll' }}
          visible={withDrawDetailModal}
          onCancel={this.cancelWithdrawDetailModal}
          footer={[
            <Button key="back" onClick={this.cancelWithdrawDetailModal}>
              关闭
            </Button>
          ]}
        >
          <div>
            {this.state.withDrawData.map(item => (
              <p>
                ID：{item.id}； 操作类型：{this.withDrawStatus[item.opType]}；
                操作时间：{item.opTime}； 备注：
                {item.remark ? item.remark : '无'}
              </p>
            ))}
          </div>
        </Modal>
      </div>
    )
  }

  render() {
    const {
      ledgerTableData,
      ledgerCurrent,
      ledgerTotal,
      ledgerLoading,
      withDrawTableData,
      withDrawCurrent,
      withDrawTotal,
      withDrawLoading,
      lastWithDrawAmount,
      totalBalance,
      totalWithDrawAmount
    } = this.state

    return (
      <PageHeaderWrapper>
        {this.renderWithDraw()}
        {this.renderWithDrawDetail()}
        <Card bordered={false}>
          <div>
            <Row>
              <Col span={24}>
                <Row gutter={20}>
                  <Col
                    style={{
                      height: '40px',
                      lineHeight: '40px',
                      fontSize: '18px'
                    }}
                  >
                    账户余额：
                    <span
                      style={{
                        color: 'green',
                        fontSize: '24px',
                        fontWeight: 'bold'
                      }}
                    >
                      {totalBalance}
                    </span>
                    &emsp;元
                  </Col>
                </Row>
                <Row gutter={20}>
                  <Col
                    span={12}
                    style={{
                      height: '40px',
                      lineHeight: '40px',
                      fontSize: '18px'
                    }}
                  >
                    已申请提现金额：
                    <span
                      style={{
                        color: 'red',
                        fontSize: '24px',
                        fontWeight: 'bold'
                      }}
                    >
                      {lastWithDrawAmount}
                    </span>
                    &emsp;元
                  </Col>
                  <Col span={12} style={{ lineHeight: '40px' }}>
                    <Button
                      type="primary"
                      onClick={() => this.showWithdrawModal()}
                    >
                      申请提现
                    </Button>
                  </Col>
                </Row>
                <Row>
                  <Col
                    style={{
                      height: '40px',
                      lineHeight: '40px',
                      fontSize: '14px'
                    }}
                  >
                    累计提现金额：
                    <span style={{ color: '#1890ff', fontSize: '14px' }}>
                      {totalWithDrawAmount}
                    </span>
                    &emsp;元
                  </Col>
                </Row>
              </Col>
            </Row>
          </div>
        </Card>
        <Card bordered={false} style={{ marginTop: 20 }}>
          <Tabs type="card">
            <TabPane tab="资金流水列表" key="1">
              <Table
                scroll={{ x: true }}
                columns={this.ledgerColumns}
                loading={ledgerLoading}
                dataSource={ledgerTableData}
                rowKey={record => record.id}
                pagination={{
                  current: ledgerCurrent,
                  total: ledgerTotal,
                  onChange: this.ledgerOnChange,
                  showTotal: this.showLedgerTotal,
                  showQuickJumper: true,
                  pageSizeOptions: ['5', '10', '20'],
                  showSizeChanger: true,
                  onShowSizeChange: this.onShowSizeChange
                }}
              />
            </TabPane>
            <TabPane tab="提现申请表" key="2">
              <Table
                scroll={{ x: true }}
                columns={this.withDrawColumns}
                loading={withDrawLoading}
                dataSource={withDrawTableData}
                rowKey={record => record.id}
                pagination={{
                  current: withDrawCurrent,
                  total: withDrawTotal,
                  onChange: this.withdrawOnChange,
                  showTotal: this.showWithDrawTotal,
                  showQuickJumper: true,
                  pageSizeOptions: ['5', '10', '20'],
                  showSizeChanger: true,
                  onShowSizeChange: this.withdrawOnShowSizeChange
                }}
              />
            </TabPane>
          </Tabs>
        </Card>
      </PageHeaderWrapper>
    )
  }
}

export default Bills
